package _interview100;

import java.util.ArrayList;
import java.util.List;

/**
 * 51. N 皇后
 */
public class No51 {
    private List<List<String>> ans;
    private List<Integer> path;
    private int n;

    public List<List<String>> solveNQueens(int n) {
        this.ans = new ArrayList<>();
        this.path = new ArrayList<>();
        this.n = n;

        dfs(0);

        return ans;
    }

    private void dfs(int row) {
        if (row == n) {
            List<String> list = new ArrayList<>();
            for (Integer i : path) {
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < n; j++) {
                    sb.append(j == i ? "Q" : ".");
                }
                list.add(sb.toString());
            }
            ans.add(list);
            return;
        }

        for (int column = 0; column < n; column++) {
            if (path.contains(column) || !isValid(row, column)) continue;
            path.add(column);
            dfs(row + 1);
            path.remove(path.size() - 1);
        }
    }

    private boolean isValid(int row, int column) {
        for (int i = 0; i < path.size(); i++) {
            Integer j = path.get(i);
            if (i - j == row - column || i + j == row + column) return false;
        }
        return true;
    }
}
